import './index.scss';
import React, { FC, ReactElement, useCallback, useState } from 'react';
import { IPhones } from '../../typings';
import { useColor, useVersion } from './hooks';
import { useSelectorCount } from '../../hooks';

import Banner from './Banner';
import Title from './Title';
import Price from './Price';
import Selector from '../Selector';
import ColorGroup from './ColorGroup';
import VersionGroup from './VersionGroup';
import Bottom from './Bottom';

interface IProps {
  phoneDetail: IPhones;
  cid: number;
  vid: number;
  totalCount: number;
}

const DetailPage: FC<IProps> = ({
  phoneDetail,
  cid,
  vid,
  totalCount
}): ReactElement => {
  const { name, color, version, limit } = phoneDetail;

  /**
   * 备注：只要用户有点击颜色选择/版本选择，视图就会显示对应的图片展示，此时就要做数据响应式处理
   */

  //找到当前颜色的那一项
  //注意：cid需要是响应式数据(本组件)
  //更新过程(versionId同理)：父组件传入默认值cid -> 变为本组件响应式数据 -> colorId变更 -> 重新执行hooks(包括自定义) -> 得到新的currentColor -> 视图根据currentColor数据重新渲染更新
  const [colorId, setColorId] = useState<number>(cid);
  const [versionId, setVersionId] = useState<number>(vid);

  //根据colorId找到对应项的当前手机颜色项
  const currentColor = useColor(color, colorId);

  /**
   console.log(currentColor);
   * {cid: 1, mark: 'black', title: '黑色', img: 'https://img10.360bu...jpg'}
   */

  //根据versionId找到对应项的当前手机版本项
  const currentVersion = useVersion(version, versionId);
  // console.log(currentVersion);
  //{vid: 1, mark: '128', title: '128GB', price: 7999}

  //根据限制数量决定可选择的数量点击次数
  const [count, setCurrentCount] = useSelectorCount(totalCount, limit);

  //点击加入购物车按钮 useCallback缓存子组件避免重复执行回调函数程序(除非依赖有更新)
  const addToCart = useCallback((total: number) => {
    console.log(total);
  }, []);

  return (
    <div className="detail-wrapper">
      <Banner img={currentColor.img} name={name} />
      <div className="info-wrap">
        <Title
          name={name}
          color={currentColor.title}
          version={currentVersion.title}
        />
        <Price limit={limit} price={currentVersion.price} />
        <Selector count={count} setCount={setCurrentCount} />
        <ColorGroup colorId={colorId} colors={color} setColorId={setColorId} />
        <VersionGroup
          versionId={versionId}
          versions={version}
          setVersionId={setVersionId}
        />
      </div>
      <Bottom
        price={currentVersion.price}
        count={count}
        addToCart={addToCart}
      />
    </div>
  );
};

export default DetailPage;
